﻿Imports HslCommunication.Profinet.Siemens
Imports HslCommunication.LogNet
Public Class frmFLBServers
    Private g_szInitFileName As String
    Private g_PLC_IP As String
    Private th As Threading.Thread
    Private _PLC_connect_Success As Boolean
    Private _Reader_connect_Success As Boolean
    Private _PLC As SiemensS7Net
    Private plcAdd As New PLC_ADDRESS
    Private plcVal As New PLC_Value
    Private objDB As New clsFLBinfo
    Private objReader1 As clsReader '读码器
    Private logfile As ILogNet
    Private dtFLBInfo As DataTable
    Private Sub frmFLBServers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)

        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If
        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\FLB.ini"
        plcAdd.r_Box_In = GetIniFile("ADDRESS", "r_Box_In", "", g_szInitFileName)
        plcAdd.r_direction = GetIniFile("ADDRESS", "r_direction", "", g_szInitFileName)
        plcAdd.r_Current_num = GetIniFile("ADDRESS", "r_Current_num", "", g_szInitFileName)
        plcAdd.r_Box_Relea = GetIniFile("ADDRESS", "r_Box_Relea", "", g_szInitFileName)
        plcAdd.w_Box_Type = GetIniFile("ADDRESS", "w_Box_Type", "", g_szInitFileName)
        plcAdd.w_Piece_Type = GetIniFile("ADDRESS", "w_Piece_Type", "", g_szInitFileName)
        plcAdd.w_plan_num = GetIniFile("ADDRESS", "w_plan_num", "", g_szInitFileName)
        plcAdd.w_Read_Successed = GetIniFile("ADDRESS", "w_Read_Successed", "", g_szInitFileName)
        plcAdd.w_Read_failed = GetIniFile("ADDRESS", "w_Read_failed", "", g_szInitFileName)

        '连接数据库
        connectDB()

        dtFLBInfo = objDB.selectUnused
        dgvlist.DataSource = dtFLBInfo

        '连接PLC
        ConnectPLC()

        '实例化读码器
        Dim dtFLBReader As DataTable
        dtFLBReader = objDB.selectByWorkshop(g_cj_pt)
        Dim drsSMQ1 As DataRow()
        drsSMQ1 = dtFLBReader.Select("equip_type_id='" & g_equipType_smq & "' and equip_id= 'Scaner0'")
        If DBNULLtoBlank(drsSMQ1(0)("ip")) <> "" Then
            _Reader_connect_Success = My.Computer.Network.Ping(drsSMQ1(0)("ip"))
            tsslbl_Reader.Text = String.Format("读码器连接：" & _Reader_connect_Success)
        End If
        objReader1 = New clsReader(drsSMQ1(0)("ip"), drsSMQ1(0)("port"))

        th = New Threading.Thread(AddressOf readPLC)
        th.Start()
    End Sub

    Private Sub ConnectPLC()
        g_PLC_IP = GetIniFile("PLC", "IP", "", g_szInitFileName)

        If _PLC_connect_Success Then
            Me._PLC.ConnectClose()
            _PLC_connect_Success = False
        End If
        _PLC = New SiemensS7Net(SiemensPLCS.S1200)
        _PLC.IpAddress = g_PLC_IP
        _PLC.Port = 102
        _PLC_connect_Success = _PLC.ConnectServer().IsSuccess()
        tsslbl_PLC.Text = String.Format("PLC连接状态：{0}", _PLC_connect_Success)
    End Sub
    Delegate Sub PLC_connect_Delegate()
    Dim PLC_connectCaller As New PLC_connect_Delegate(AddressOf ConnectPLC)

    Delegate Sub saveDelegate()
    Dim saveCaller As New saveDelegate(AddressOf save)
    Delegate Sub callreaderDelegate()
    Dim callreaderCaller As New saveDelegate(AddressOf callreader)
    Private Sub save()

        If objDB.insert(plcVal) = -2 Then
            '写LOG
            logfile.WriteError("保存失败。")
        Else
            dtFLBInfo = objDB.selectUnused
            dgvlist.DataSource = dtFLBInfo
            plcVal.r_Current_num_value = _PLC.ReadInt16(plcAdd.r_Current_num).Content '片数
            _PLC.Write(plcAdd.r_Current_num, IIf(plcVal.r_Current_num_value > 2, plcVal.r_Current_num_value - 2, plcVal.r_Current_num_value - plcVal.r_Current_num_value))
        End If
    End Sub

    Private Sub callreader()
        If _Reader_connect_Success Then
            objReader1.read()
            If objReader1.QR_CODE = "" Then
                _PLC.Write(plcAdd.w_Read_Successed, False)
                _PLC.Write(plcAdd.w_Read_failed, True)
            Else
                _PLC.Write(plcAdd.w_Read_Successed, True)
                _PLC.Write(plcAdd.w_Read_failed, False)
                plcVal.dl_no_value = objReader1.QR_CODE
            End If
        End If
    End Sub

    Private Sub readPLC()
        While True
            If _PLC_connect_Success = True Then
                plcVal.r_Box_In_value = _PLC.ReadBool(plcAdd.r_Box_In).Content '允许读料框号
                plcVal.r_direction_value = _PLC.ReadInt16(plcAdd.r_direction).Content '翻转设定
                plcVal.r_Current_num_value = _PLC.ReadInt16(plcAdd.r_Current_num).Content '片数
                plcVal.r_Box_Relea_value = _PLC.ReadBool(plcAdd.r_Box_Relea).Content '满框放行
                plcVal.w_Piece_Type_value = _PLC.ReadBool(plcAdd.w_Piece_Type).Content '满框放行

                '允许读料框号
                If plcVal.r_Box_In_value Then
                    Dim _result As IAsyncResult
                    _result = Me.BeginInvoke(callreaderCaller)
                    callreaderCaller.EndInvoke(_result)
                End If

                '满框放行
                If plcVal.r_Box_Relea_value Then
                    Dim _result As IAsyncResult
                    _result = Me.BeginInvoke(saveCaller)
                    saveCaller.EndInvoke(_result)
                End If
            Else
                PLC_connectCaller.Invoke
            End If

        End While

    End Sub

    Private Sub frmFLBServers_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        Try

            If th.IsAlive Then th.Abort()
            DBacs.Disconnect()
        Catch ex As Exception
            logfile.WriteError("关闭画面时出错:", ex.Message)
        End Try
    End Sub
End Class
Public Class PLC_ADDRESS
    Public r_Box_In As String
    Public r_direction As String
    Public r_Current_num As String
    Public r_Box_Relea As String
    Public w_Box_Type As String
    Public w_Piece_Type As String
    Public w_plan_num As String
    Public w_Read_Successed As String
    Public w_Read_failed As String
End Class
Public Class PLC_Value
    Public r_Box_In_value As Boolean      '允许读料框号
    Public r_direction_value As Integer   '翻转设定
    Public r_Current_num_value As Integer '片数
    Public r_Box_Relea_value As Boolean   '满框放行
    'Public w_Box_Type As String
    Public w_Piece_Type_value As String   '法兰板型号
    Public dl_no_value As String
    'Public w_plan_num As String
    'Public w_Read_Successed As String
    'Public w_Read_failed As String
End Class
Public Class clsFLBinfo
    Public Function selectUnused() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT flb_type,dl_no,which_side,piece_num,update_time FROM sf.b_flb_info "
        szSql &= "WHERE status<>'2' order by update_time desc "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectUnused = New DataTable
        Else
            selectUnused = rtn
        End If
        Return rtn
    End Function

    Public Function insert(flbInfo As PLC_Value) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer

        Try
            szSql &= "	INSERT INTO sf.b_flb_info(factory_id , dl_no , flb_type ,"
            szSql &= "	which_side , piece_num , used_piece_num , status , operator ,  update_time) 	 "
            szSql &= "	VALUES (  ? ,? , ? , ? , ? , ? , ? ,  ? , (SELECT CURRENT_TIMESTAMP(6)))	 "
            With flbInfo
                rtn = DBacs.ExecuteUpdateSql(szSql, -1, g_factory_id, .dl_no_value, .w_Piece_Type_value, .r_direction_value,
                                             IIf(.r_Current_num_value > 2, 2, .r_Current_num_value), 0, "0", "Auto")
            End With
        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function
    Public Function selectByWorkshop(ws As String) As DataTable
        Dim szSql As String = String.Empty
        szSql &= "SELECT * "
        szSql &= "  FROM sf.t_hw_setting "
        szSql &= "  WHERE factory_id =? "
        szSql &= "  AND workshop_id = ? "
        szSql &= "  ORDER BY workshop_id,equip_id "

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1, g_factory_id, ws)
        If IsNothing(dt) Then
            selectByWorkshop = New DataTable
        Else
            selectByWorkshop = dt
        End If
    End Function
End Class
